package com.bcu.cn.onlineexamsystem.adminmanage.controller;

import com.bcu.cn.onlineexamsystem.adminmanage.entity.AdminUser;
import com.bcu.cn.onlineexamsystem.adminmanage.service.AdminUserService;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Course;
import com.bcu.cn.onlineexamsystem.exammanage.entity.Class;
import com.bcu.cn.onlineexamsystem.exammanage.mapper.CourseMapper;
import com.bcu.cn.onlineexamsystem.exammanage.mapper.ClassMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/admin")
public class AdminUserController {

    private final AdminUserService userService;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private ClassMapper classMapper;

    @Autowired
    public AdminUserController(AdminUserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public String userManagement(HttpSession session, Model model) {
        // 验证管理员权限
        Object user = session.getAttribute("user");
        if (user == null || !"admin".equals(((com.bcu.cn.onlineexamsystem.user.entity.User) user).getRole())) {
            return "redirect:/login";
        }
        model.addAttribute("users", userService.getAllUsers());
        model.addAttribute("classes", userService.getAllClasses());
        return "admin/home";
    }

    @PostMapping("/users/add")
    public String addUser(AdminUser user, HttpSession session) {
        // 验证管理员权限
        if (!isAdmin(session)) return "redirect:/login";

        userService.createUser(user);
        return "redirect:/admin/users";
    }

    @PostMapping("/users/update")
    public String updateUser(AdminUser user, HttpSession session) {
        if (!isAdmin(session)) return "redirect:/login";

        userService.updateUser(user);
        return "redirect:/admin/users";
    }

    @GetMapping("/users/delete/{userId}")
    public String deleteUser(@PathVariable String userId, HttpSession session) {
        if (!isAdmin(session)) return "redirect:/login";

        userService.deleteUser(userId);
        return "redirect:/admin/users";
    }

    private boolean isAdmin(HttpSession session) {
        Object user = session.getAttribute("user");
        return user != null && "admin".equals(((com.bcu.cn.onlineexamsystem.user.entity.User) user).getRole());
    }

    @GetMapping("/users/search")
    public String searchUsers(@RequestParam(required = false) String keyword,
                              @RequestParam(required = false) String role,
                              HttpSession session,
                              Model model) {
        // 验证管理员权限
        if (!isAdmin(session)) return "redirect:/login";
        model.addAttribute("users", userService.searchUsers(keyword, role));
        model.addAttribute("classes", userService.getAllClasses());
        return "admin/home";
    }

    // 数据大屏统计接口
    @GetMapping("/users/dashboard/data")
    @ResponseBody
    public Map<String, Object> dashboardData() {
        Map<String, Object> result = new HashMap<>();
        // 用户总数、各角色人数
        int userCount = userService.countAllUsers();
        int studentCount = userService.countByRole("student");
        int teacherCount = userService.countByRole("teacher");
        int adminCount = userService.countByRole("admin");
        int classCount = userService.countAllClasses();
        result.put("userCount", userCount);
        result.put("studentCount", studentCount);
        result.put("teacherCount", teacherCount);
        result.put("adminCount", adminCount);
        result.put("classCount", classCount);
        // 用户增长趋势（近7天）
        List<String> trendDates = new ArrayList<>();
        List<Integer> trendCounts = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        for (int i = 6; i >= 0; i--) {
            cal.setTime(new Date());
            cal.add(Calendar.DATE, -i);
            Date day = cal.getTime();
            String dateStr = new java.text.SimpleDateFormat("yyyy-MM-dd").format(day);
            trendDates.add(dateStr);
            trendCounts.add(userService.countUsersByDate(dateStr));
        }
        result.put("trendDates", trendDates);
        result.put("trendCounts", trendCounts);
        return result;
    }

    // 获取所有课程
    @GetMapping("/users/all-courses")
    @ResponseBody
    public List<Course> allCourses() {
        return courseMapper.findAll();
    }

    // 获取所有班级
    @GetMapping("/users/all-classes")
    @ResponseBody
    public List<Class> allClasses() {
        return classMapper.findAll();
    }

    // 获取老师已分配课程ID
    @GetMapping("/users/teacher/{teacherId}/courses")
    @ResponseBody
    public List<Long> teacherCourses(@PathVariable String teacherId) {
        return userService.getTeacherCourseIds(teacherId);
    }

    // 获取老师已分配班级ID
    @GetMapping("/users/teacher/{teacherId}/classes")
    @ResponseBody
    public List<Long> teacherClasses(@PathVariable String teacherId) {
        return userService.getTeacherClassIds(teacherId);
    }

    // 保存老师课程分配
    @PostMapping("/users/teacher/{teacherId}/assign-courses")
    @ResponseBody
    public String assignTeacherCourses(@PathVariable String teacherId, @RequestBody List<Long> courseIds) {
        userService.assignTeacherCourses(teacherId, courseIds);
        return "ok";
    }

    // 保存老师班级分配
    @PostMapping("/users/teacher/{teacherId}/assign-classes")
    @ResponseBody
    public String assignTeacherClasses(@PathVariable String teacherId, @RequestBody List<Long> classIds) {
        userService.assignTeacherClasses(teacherId, classIds);
        return "ok";
    }

    // 获取学生已分配课程ID
    @GetMapping("/users/student/{studentId}/courses")
    @ResponseBody
    public List<Long> studentCourses(@PathVariable String studentId) {
        return userService.getStudentCourseIds(studentId);
    }

    // 保存学生课程分配
    @PostMapping("/users/student/{studentId}/assign-courses")
    @ResponseBody
    public String assignStudentCourses(@PathVariable String studentId, @RequestBody List<Long> courseIds) {
        userService.assignStudentCourses(studentId, courseIds);
        return "ok";
    }

    /**
     * 管理员个人信息页
     */
    @GetMapping("/profile")
    public String adminProfile(HttpSession session, Model model) {
        Object user = session.getAttribute("user");
        if (user == null || !"admin".equals(((com.bcu.cn.onlineexamsystem.user.entity.User) user).getRole())) {
            return "redirect:/login";
        }
        String userId = ((com.bcu.cn.onlineexamsystem.user.entity.User) user).getUserId();
        AdminUser admin = userService.getUserById(userId);
        model.addAttribute("admin", admin);
        return "admin/profile";
    }

    /**
     * 管理员个人信息修改
     */
    @PostMapping("/profile/update")
    public String updateAdminProfile(@ModelAttribute com.bcu.cn.onlineexamsystem.adminmanage.entity.AdminUser adminUser, HttpSession session, Model model) {
        Object user = session.getAttribute("user");
        if (user == null || !"admin".equals(((com.bcu.cn.onlineexamsystem.user.entity.User) user).getRole())) {
            return "redirect:/login";
        }
        // 只允许修改自己的信息
        String userId = ((com.bcu.cn.onlineexamsystem.user.entity.User) user).getUserId();
        if (!userId.equals(adminUser.getUserId())) {
            model.addAttribute("error", "只允许修改自己的信息");
            return "redirect:/admin/profile";
        }
        // 保证role为admin
        adminUser.setRole("admin");
        userService.updateUser(adminUser);
        // 更新session中的userName等信息
        ((com.bcu.cn.onlineexamsystem.user.entity.User) user).setUserName(adminUser.getUserName());
        ((com.bcu.cn.onlineexamsystem.user.entity.User) user).setRealName(adminUser.getRealName());
        ((com.bcu.cn.onlineexamsystem.user.entity.User) user).setEmail(adminUser.getEmail());
        ((com.bcu.cn.onlineexamsystem.user.entity.User) user).setPhone(adminUser.getPhone());
        session.setAttribute("user", user);
        return "redirect:/admin/profile";
    }

}